package com.sdx.console.question.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.answer.service.QaAnswerService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.mockito.internal.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.question.entity.*;
import com.sdx.console.question.service.*;
import com.sdx.console.question.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * question 接口
 */
@RequestMapping("/question/question")
@Controller
public class QaQuestionController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(QaQuestionController.class);
    private static final String MODEL = "/question/question";

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
	private QaQuestionService questionService;
    @Resource
    private FileService fileService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private QaAnswerService qaAnswerService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
        view.addObject("customerInfoList",customerInfoList);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("question.question.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("question.question.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer questionId,String isAnswer) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        if(StringUtils.equals(isAnswer,"Y")){
             view = new ModelAndView(MODEL+"/answer.html");
        }
        QaQuestion question = questionService.queryById(questionId);
        view.addObject("question", question);
		setPageParam(view,request);
		try {
			view.addObject("questionJson", JacksonUtils.toJsonString(question,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("question.question.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("question.question.query")
    @ResponseBody
    public JsonResult<PageQuery> list(QaQuestion condtion)
    {
        PageQuery page = condtion.getPageQuery();
        questionService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,QaQuestion question,HttpServletRequest request
							,MultipartFile fileFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/question/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(fileFile)) {
			try
			{
		        String fileFileNamePair = FileUtils.upload(subPath,fileFile);
		        String fileStoreFile = fileFileNamePair.split("::")[0];
		        fileStoreFile = subPath+fileStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+fileStoreFile,bucketName,fileStoreFile.substring(1));
				String fileUrl = "https://sdxcomm."+ConfigService.ossDomain+fileStoreFile;
				question.setFile(fileUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,fileStoreFile,fileUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			question.setCreateTime(new Date());
			questionService.save(question);
		} else {
			questionService.updateTemplate(question);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("question.question.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)QaQuestion question,HttpServletRequest request
							,@RequestParam("fileFile") MultipartFile fileFile
		)
    {

        return save(true,question,request
					,fileFile
		);
    }

    @PostMapping("/update.json")
    @Function("question.question.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  QaQuestion question,HttpServletRequest request
							,@RequestParam("fileFile") MultipartFile fileFile
		) {
		return save(false,question,request
		,fileFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("question.question.query")
    @ResponseBody
    public JsonResult<QaQuestion>queryInfo(Integer questionId) {
        QaQuestion question = questionService.queryById( questionId);
        return  JsonResult.success(question);
    }

    @PostMapping("/delete.json")
    @Function("question.question.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        questionService.batchDelQaQuestion(idList);

        // 删除相关回答
        
        return JsonResult.success();
    }
    
    
    @PostMapping("/excel/export.json")
    @Function("question.question.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,QaQuestionQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此questionService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/question/question/你的excel模板文件名字.xls";
        PageQuery<QaQuestion> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<QaQuestion> list =questionService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("question_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping("/excel/import.do")
    @Function("question.question.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }

}
